package com.minglead.crawler.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.minglead.crawler.constant.YqModelAnalysisConstant;
import com.minglead.crawler.entity.YqLabelScoreEntity;
import com.minglead.crawler.exception.BizCommonException;
import com.minglead.crawler.service.YqModelAnalysisService;
import com.minglead.crawler.shell.GosShell;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class YqModelAnalysisServiceImpl implements YqModelAnalysisService {

    /**
     * 行业分析(文件数据末尾必须有个回车符)
     * @param input 文件路径或单篇文章
     * @param isSingle 是否为单篇文章
     * @return 结果对象
     */
    @Override
    public List<List<YqLabelScoreEntity>> getDomain(String input, boolean isSingle) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.domainModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //run.sh脚本文件的绝对路径
        String shellFilePath = modelPath + "/run.sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        String sourceFilePath = input;
        //是否为单篇文章
        if (isSingle) {
            sourceFilePath = modelPath + "/sourceFile/" + uuid + ".txt";
            // 创建所有中间目录
            createDirectory(modelPath + "/sourceFile");
            //去除末尾所有换行符
            String input2 = input.trim().replaceAll("\\s+$", "");
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFilePath))){
                writer.write(input2);
                writer.flush();
            } catch (IOException e) {
                throw new BizCommonException("写入单条数据到文件出错");
            }
        }
        try {
            // 创建所有中间目录
            createDirectory(modelPath + "/result");
            //添加末尾回车
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFilePath, true))){
                writer.write("\n");
                writer.flush();
            } catch (IOException e) {
                throw new BizCommonException("添加末尾回车出错");
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            writer.write("#!/bin/bash"); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write("INPUT_FILE=" + sourceFilePath);
            writer.newLine(); // 换行
            writer.write("NLP_PATH=" + YqModelAnalysisConstant.modelAnalysisJobPath);
            writer.newLine(); // 换行
            writer.write("$NLP_PATH/fastText-0.9.2/fasttext predict-prob $NLP_PATH/nlp_domain_classification_chinese/pytorch_model.bin $INPUT_FILE 3");
            writer.newLine(); // 换行
            // 关闭文件写入对象
            writer.close();
        } catch (IOException e) {
            throw new BizCommonException("脚本写入出错");
        }
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        //解析结果数据文件 构造返回结果
        List<List<YqLabelScoreEntity>> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(logPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("__label__")) {
                    list.add(parseDomainLabelScores(line));
                }
            }
        } catch (IOException e) {
            throw new BizCommonException("读取结果文件出错");
        }
        return list;
    }

    /**
     * 行业分析
     * @param input 文件路径
     * @return 结果文件路径
     */
    @Override
    public String getDomain(String input) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.domainModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //run.sh脚本文件的绝对路径
        String shellFilePath = modelPath + File.separator + "run.sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            BufferedWriter writer = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            writer.write("#!/bin/bash"); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write("INPUT_FILE=" + input);
            writer.newLine(); // 换行
            writer.write("NLP_PATH=" + YqModelAnalysisConstant.modelAnalysisJobPath);
            writer.newLine(); // 换行
            writer.write("$NLP_PATH/fastText-0.9.2/fasttext predict-prob $NLP_PATH/nlp_domain_classification_chinese/pytorch_model.bin $INPUT_FILE 3");
            writer.newLine(); // 换行
            // 关闭文件写入对象
            writer.close();
        } catch (IOException e) {
            throw new BizCommonException("脚本写入出错");
        }
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        return logPath;
    }

    public static List<YqLabelScoreEntity> parseDomainLabelScores(String input) {
        List<YqLabelScoreEntity> labelScores = new ArrayList<>();
        String[] parts = input.split("__label__");
        for (int i = 1; i < parts.length; i++) {
            String part = parts[i].trim();
            String[] splitPart = part.split(" ");
            if (splitPart.length == 2) {
                String label = splitPart[0];
                float score = Float.parseFloat(splitPart[1]);
                labelScores.add(new YqLabelScoreEntity(label, score));
            }
        }
        return labelScores;
    }

    /**
     * 情感分析
     * @param input 文件路径或单篇文章
     * @param isSingle 是否为单篇文章
     * @return 结果对象
     */
    @Override
    public List<List<YqLabelScoreEntity>> getSentiment(String input, boolean isSingle) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.sentimentModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //python脚本文件路径
        String pyPath = resultPath + uuid + ".py";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        String sourceFilePath = input;
        //是否为单篇文章
        if (isSingle) {
            sourceFilePath = modelPath + "/sourceFile/" + uuid + ".txt";
            try {
                // 创建所有中间目录
                createDirectory(modelPath + "/sourceFile");
                BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFilePath));
                writer.write(input);
                writer.close();
            } catch (IOException e) {
                throw new BizCommonException("写入单条数据到文件出错");
            }
        }
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            // 创建 Python 脚本文件
            String pythonScript = buildSentimentPythonScript(sourceFilePath, modelPath);
            BufferedWriter pyWriter = new BufferedWriter(new FileWriter(pyPath));
            pyWriter.write(pythonScript);
            pyWriter.close();
            BufferedWriter shWriter = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            shWriter.write("#!/bin/bash"); // 设置脚本解释器
            shWriter.newLine(); // 换行
//            shWriter.write("source /home/gosadmin/.bashrc;"); // 设置脚本解释器
            shWriter.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write("conda activate " + YqModelAnalysisConstant.CONDA_PATH + "/modelscope-py39;");
            shWriter.newLine(); // 换行
            shWriter.write("python " + pyPath); // 写入脚本命令
            shWriter.newLine(); // 换行
            // 关闭文件写入对象
            shWriter.close();
        } catch (IOException e) {
            throw new BizCommonException(".sh脚本文件写入出错");
        }
        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        //解析结果数据文件 构造返回结果
        List<List<YqLabelScoreEntity>> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(logPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("{'scores':")) {
                    list.add(parseSentimentLabelScores(line));
                }
            }
        } catch (IOException e) {
            throw new BizCommonException("读取结果文件出错");
        }
        return list;
    }

    /**
     * 情感分析
     * @param input 文件路径
     * @return 结果文件路径
     */
    @Override
    public String getSentiment(String input) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.sentimentModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //python脚本文件路径
        String pyPath = resultPath + uuid + ".py";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            // 创建 Python 脚本文件
            String pythonScript = buildSentimentPythonScript(input, modelPath);
            BufferedWriter pyWriter = new BufferedWriter(new FileWriter(pyPath));
            pyWriter.write(pythonScript);
            pyWriter.close();
            BufferedWriter shWriter = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            shWriter.write("#!/bin/bash"); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write("conda activate " + YqModelAnalysisConstant.CONDA_PATH + "/modelscope-py39;");
            shWriter.newLine(); // 换行
            shWriter.write("python " + pyPath); // 写入脚本命令
            shWriter.newLine(); // 换行
            // 关闭文件写入对象
            shWriter.close();
        } catch (IOException e) {
            throw new BizCommonException(".sh脚本文件写入出错");
        }
        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        return logPath;
    }

    public static List<YqLabelScoreEntity> parseSentimentLabelScores(String input) {
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(input, JsonObject.class);
        JsonArray scoresArray = jsonObject.getAsJsonArray("scores");
        JsonArray labelsArray = jsonObject.getAsJsonArray("labels");
        List<YqLabelScoreEntity> resultList = new ArrayList<>();
        if (scoresArray != null && labelsArray != null && scoresArray.size() == labelsArray.size()) {
            for (int i = 0; i < scoresArray.size(); i++) {
                float score = scoresArray.get(i).getAsFloat();
                String label = labelsArray.get(i).getAsString();
                resultList.add(new YqLabelScoreEntity(label, score));
            }
        }
        return resultList;
    }

    /**
     * 类别分析
     * @param input 文件路径或单篇文章
     * @param topN 输出得分最高的前n个类别
     * @param isSingle 是否为单篇文章
     * @return 结果对象
     */
    @Override
    public List<List<YqLabelScoreEntity>> getThutct(String input, int topN, boolean isSingle) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.thuctcModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //jar包路径
        String jarPath = modelPath + "/THUCTC_java_v1/out/artifacts/THUCTC_java_v1_jar/THUCTC_java_v1.jar";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        String sourceFilePath = input;
        //是否为单篇文章
        if (isSingle) {
            sourceFilePath = modelPath + "/sourceFile/" + uuid + ".txt";
            try {
                // 创建所有中间目录
                createDirectory(modelPath + "/sourceFile");
                BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFilePath));
                writer.write(input);
                writer.flush();
                writer.close();
            } catch (IOException e) {
                throw new BizCommonException("写入单条数据到文件出错");
            }
        }
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            BufferedWriter writer = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            writer.write("#!/bin/bash"); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write("java -jar " + jarPath + " -l " + modelPath + "/news_model" + " -n " + topN + " -s " + sourceFilePath + " -r " + logPath); // 写入脚本命令
            writer.newLine(); // 换行
            // 关闭文件写入对象
            writer.close();
        } catch (IOException e) {
            throw new BizCommonException("脚本写入出错");
        }
        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        //解析结果数据文件 构造返回结果
        List<List<YqLabelScoreEntity>> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(logPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(parseThutctAndKeywordLabelScores(line));
            }
        } catch (IOException e) {
            throw new BizCommonException("读取结果文件出错");
        }
        //删除最后1行
        return (list.size() > 1) ? list.subList(0, list.size() - 1) : new ArrayList<>();
    }

    /**
     * 类别分析
     * @param input 文件路径
     * @param topN 输出得分最高的前n个类别
     * @return 结果文件路径
     */
    @Override
    public String getThutct(String input, int topN) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.thuctcModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //jar包路径
        String jarPath = modelPath + "/THUCTC_java_v1/out/artifacts/THUCTC_java_v1_jar/THUCTC_java_v1.jar";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            BufferedWriter writer = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            writer.write("#!/bin/bash"); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            writer.newLine(); // 换行
            writer.write("java -jar " + jarPath + " -l " + modelPath + "/news_model" + " -n " + topN + " -s " + input + " -r " + logPath); // 写入脚本命令
            writer.newLine(); // 换行
            writer.flush();
            // 关闭文件写入对象
            writer.close();
        } catch (IOException e) {
            throw new BizCommonException("脚本写入出错");
        }
        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        return logPath;
    }

    public static List<YqLabelScoreEntity> parseThutctAndKeywordLabelScores(String input) {
        List<YqLabelScoreEntity> resultList = new ArrayList<>();
        String[] parts = input.trim().split(" ");
        for (String part : parts) {
            String[] keyValue = part.split(",");
            if (keyValue.length == 2) {
                String label = keyValue[0];
                float score = Float.parseFloat(keyValue[1]);
                resultList.add(new YqLabelScoreEntity(label, score));
            }
        }
        return resultList;
    }

    /**
     * 关键词分析
     * @param input 文件路径或单篇文章
     * @param topN 输出得分最高的前n个类别
     * @param minWordNum 单个关键词的最小中文数
     * @param isSingle 是否为单篇文章
     * @return 结果对象
     */
    @Override
    public List<List<YqLabelScoreEntity>> getKeyword(String input, int topN, int minWordNum, boolean isSingle) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.keywordModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //python脚本文件路径
        String pyPath = resultPath + uuid + ".py";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        String sourceFilePath = input;
        //是否为单篇文章
        if (isSingle) {
            sourceFilePath = modelPath + "/sourceFile/" + uuid + ".txt";
            try {
                // 创建所有中间目录
                createDirectory(modelPath + "/sourceFile");
                BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFilePath));
                writer.write(input);
                writer.close();
            } catch (IOException e) {
                throw new BizCommonException("写入单条数据到文件出错");
            }
        }
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            // 创建 Python 脚本文件
            String pythonScript = buildKeywordPythonScript(sourceFilePath, topN, minWordNum);
            BufferedWriter pyWriter = new BufferedWriter(new FileWriter(pyPath));
            pyWriter.write(pythonScript);
            pyWriter.close();
            BufferedWriter shWriter = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            shWriter.write("#!/bin/bash"); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write("conda activate " + YqModelAnalysisConstant.CONDA_PATH + "/github-py34;");
            shWriter.newLine(); // 换行
            shWriter.write("python " + pyPath); // 写入脚本命令
            shWriter.newLine(); // 换行
            // 关闭文件写入对象
            shWriter.close();
        } catch (IOException e) {
            throw new BizCommonException(".sh脚本文件写入出错");
        }
        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        //解析结果数据文件 构造返回结果
        List<List<YqLabelScoreEntity>> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(logPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(parseThutctAndKeywordLabelScores(line));
            }
        } catch (IOException e) {
            throw new BizCommonException("读取结果文件出错");
        }
        //删除数据的前6行和最后1行
        return (list.size() > 7) ? list.subList(6, list.size() - 1) : new ArrayList<>();
    }

    /**
     * 关键词分析
     * @param input 文件路径
     * @param topN 输出得分最高的前n个类别
     * @return 结果文件路径
     */
    @Override
    public String getKeyword(String input, int topN, int minWordNum) {
        String uuid = UUID.randomUUID().toString();
        //模型目录
        String modelPath = YqModelAnalysisConstant.modelAnalysisJobPath + File.separator + YqModelAnalysisConstant.keywordModelName;
        //脚本及分析结果文件目录
        String resultPath = modelPath + "/result/";
        //python脚本文件路径
        String pyPath = resultPath + uuid + ".py";
        //生成的shell脚本文件的绝对路径
        String shellFilePath = resultPath + uuid + ".sh";
        //输出的日志绝对路径
        String logPath = resultPath + uuid + ".log";
        try {
            // 创建所有中间目录
            createDirectory(resultPath);
            // 创建 Python 脚本文件
            String pythonScript = buildKeywordPythonScript(input, topN, minWordNum);
            BufferedWriter pyWriter = new BufferedWriter(new FileWriter(pyPath));
            pyWriter.write(pythonScript);
            pyWriter.close();
            BufferedWriter shWriter = new BufferedWriter(new FileWriter(shellFilePath));
            // 写入脚本内容
            shWriter.write("#!/bin/bash"); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write(YqModelAnalysisConstant.SOURCE_PATH); // 设置脚本解释器
            shWriter.newLine(); // 换行
            shWriter.write("conda activate " + YqModelAnalysisConstant.CONDA_PATH + "/github-py34;");
            shWriter.newLine(); // 换行
            shWriter.write("python " + pyPath); // 写入脚本命令
            shWriter.newLine(); // 换行
            // 关闭文件写入对象
            shWriter.close();
        } catch (IOException e) {
            throw new BizCommonException(".sh脚本文件写入出错");
        }

        //执行脚本获取输出
        String[] cmd = {"sh", shellFilePath};
        GosShell gosShell = new GosShell(YqModelAnalysisConstant.modelAnalysisJobPath, cmd, logPath);
        gosShell.run();
        return logPath;
    }

    // 创建所有中间目录
    private void createDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists() && !directory.mkdirs()) {
            throw new RuntimeException("Failed to create directory: " + directory.getAbsolutePath());
        }
    }

    //构造情感分析python脚本
    private static String buildSentimentPythonScript(String sourceFilePath, String modelPath) {
        return "from modelscope.pipelines import pipeline\n" +
                "from modelscope.utils.constant import Tasks\n" +
                "semantic_cls = pipeline(Tasks.text_classification, '" + modelPath + "')\n" +
                "def read_and_print_file(sourceFilePath):\n" +
                "    try:\n" +
                "        with open(sourceFilePath, 'r', encoding='utf-8') as file:\n" +
                "            for line in file:\n" +
                "                print(semantic_cls(input=line))\n" +
                "    except FileNotFoundError:\n" +
                "        print(f'文件未找到: {file_path}')\n" +
                "    except Exception as e:\n" +
                "        print(f'读取文件时发生错误: {e}')\n" +
                "sourceFilePath = '" + sourceFilePath + "'\n" +
                "read_and_print_file(sourceFilePath)";
    }

    //构造关键词分析python脚本
    private static String buildKeywordPythonScript(String sourceFilePath, int topN, int minWordNum) {
        return "from __future__ import print_function\n" +
                "import sys\n" +
                "try:\n" +
                "    reload(sys)\n" +
                "    sys.setdefaultencoding('utf-8')\n" +
                "except:\n" +
                "    pass\n" +
                "import codecs\n" +
                "from textrank4zh import TextRank4Keyword, TextRank4Sentence\n" +
                "tr4w = TextRank4Keyword()\n" +
                "def read_and_print_file(sourceFilePath):\n" +
                "    try:\n" +
                "        with open(sourceFilePath, 'r', encoding='utf-8') as file:\n" +
                "            for line in file:\n" +
                "                tr4w.analyze(text=line.strip(), lower=True, window=2)\n" +
                "                for item in tr4w.get_keywords(" + topN + ", word_min_len=" + minWordNum + "):\n" +
                "                    print(f'{item.word},{item.weight}', end=' ')\n" +
                "                print()\n" +
                "    except FileNotFoundError:\n" +
                "        print(f'文件未找到: {file_path}')\n" +
                "    except Exception as e:\n" +
                "        print(f'读取文件时发生错误: {e}')\n" +
                "sourceFilePath = '" + sourceFilePath + "'\n" +
                "read_and_print_file(sourceFilePath)";
    }
}
